﻿using System;
using System.Collections.Generic;
using System.Windows;
using TheGameClient.Processes;
using Waaahsabi.Controls.FileSystem;

namespace TheGameClient
{
	public partial class SecSysPsecControl : ISecuritySystem
	{
		private GatewayFileItem _selectedFile;
		private SecuritySystemState _state;

		public SecSysPsecControl()
		{
			// Required to initialize variables
			InitializeComponent();
		}

		#region ISecuritySystem Members

		public SecuritySystemState State
		{
			get { return _state; }
			set
			{
				_state = value;
				switch (_state)
				{
				case SecuritySystemState.None:
					VisualStateManager.GoToState(this, "Default", true);
					break;
				case SecuritySystemState.Accessed:
				case SecuritySystemState.Bypassed:
					VisualStateManager.GoToState(this, "Accessed", true);
					break;
				case SecuritySystemState.AccountCreation:
					VisualStateManager.GoToState(this, "AccountCreation", false);
					break;
				}
			}
		}

		public ulong InterfaceId
		{
			get { return new Guid("{571E7C07-39B5-4292-8A65-3C5E518E1625}").ToLong(); }
		}

		public Guid ProcessId { get; private set; }

		public InterfaceCategory Category
		{
			get { return InterfaceCategory.SecuritySystem; }
		}

		public string ProcessName
		{
			get { return "Phase shifting elliptic curve challenge/response"; }
		}

		public event EventHandler<AccessAttemptEventArgs> BypassAttempt;
		public event EventHandler<AccessAttemptEventArgs> AccessAttempt;

		public void Bypass(IProgram bypasser)
		{
			if (BypassAttempt != null)
			{
				BypassAttempt(this, new AccessAttemptEventArgs {Bypasser = bypasser});
			}
		}

		public void Access()
		{
			List<object> parameters = new List<object>
			{
				_selectedFile.FileId
			};
			if (AccessAttempt != null)
				AccessAttempt(this, new AccessAttemptEventArgs {Bypasser = null, Parameters = parameters});
		}

		public void SetBypassResult(bool successful)
		{
			if (!successful)
				return;
			VisualStateManager.GoToState(this, "Accessed", true);
		}

		public void SetAccessResult(bool successful)
		{
			if (!successful)
				return;
			VisualStateManager.GoToState(this, "Accessed", true);
		}

		#endregion

		private void BrowseButtonClick(object sender, RoutedEventArgs e)
		{
			DlgBrowseLocalFile dlg = new DlgBrowseLocalFile();
			dlg.FileFilter = ".psec";
			dlg.Closed += (_s, _e) =>
			{
				if (dlg.FileItem != null)
				{
					txtFileName.DataContext = dlg.FileItem;
					_selectedFile = dlg.FileItem;
				}
			};
			dlg.Show();
		}

		private void BtnOkClick(object sender, RoutedEventArgs e)
		{
			Access();
		}
	}

	public class SecurityPsecUiFactory : UiFactoryBase
	{
		public override InterfaceCategory UiCategory
		{
			get { return InterfaceCategory.SecuritySystem; }
		}

		public override IProcess CreateProgram()
		{
			return new SecSysPsecControl();
		}
	}
}